2023/12/231096字符

高阶组件

  • 用于抽离组件内的一些功能
  • 将组件作为参数,返回一个新组件的函数
import React, {Component} from 'react';
import ReactDOM from 'react-dom';

function withTest (Comp, str) {  // 高阶组件一般以 with 开头
    return class logWrapper extends Component {
        componentDidMount () {
            console.log(`组件${Comp.name}被创建`);
        }
        componentWillUnmount () {
            console.log(`组件${Comp.name}被销毁`);
        }
        render () {
            return <>{str}<Comp {...this.props}/></>;  // 展开传递属性,给下层组件
        }
    }
}
function A (props) {
    return (<h1>{props.a}</h1>);
}
function B (props) {
    return (<h2>{props.b}</h2>);
}

const ALog = withTest(A, 'hello');
const BLog = withTest(B);

ReactDOM.render(<>
    <ALog a={111}/>
    <BLog b={222}/>
</>, document.getElementById('root'));

不要在 render 中使用高阶组件 不要在高阶组件内部更改传入的组件 Comp.prototype.componentDidMount